<template>
    <div class="stats">
        <div class="stats-item" v-for="item in data" :key="item.id">
            <p><span>0</span></p>
            <p>{{ item.text }}</p>
        </div>
    </div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import { getRandomMultipleInRange } from "../utils/index"
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger);

const data = ref([
    { id: 1, value: getRandomMultipleInRange(2000, 260000, 1), text: 'Vehicle breakdowns prevented' },
    { id: 2, value: getRandomMultipleInRange(2000, 24000, 1), text: 'Mechanic visits recommended' },
    { id: 3, value: getRandomMultipleInRange(2000, 88000, 1), text: 'Total saved by our users' },
    { id: 4, value: getRandomMultipleInRange(2000, 22000, 1), text: 'Diagnostics errors detected' },
])

onMounted(()=>{
    const formatter = new Intl.NumberFormat('en-US', {
        style: 'decimal',
        minimumFractionDigits: 0,
        maximumFractionDigits: 0,
      });
    const spans = gsap.utils.toArray(".stats-item span");
    spans.forEach((item,index)=>{
        gsap.fromTo(item,{
            innerText:0,
            opacity:0.5
        },{
            innerText:data.value[index].value,
            opacity:1,
            duration:1,
            snap:{innerText:1},
            scrollTrigger:{
                trigger:".stats",
                start:"top center",
            },
            onUpdate:()=>{
                item.innerText = formatter.format(item.innerText);
            } 
        })
    })
    
})

</script>
<style scoped>
.stats {
    display: flex;
    height: 20vw;
    background-color: #f35d40;
    color: #fff;
    padding: 3vw;
    box-sizing: border-box;
    text-align: center;
}

.stats-item {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.stats-item:not(:last-child) {
    border-right: 1px solid #fff;
}

p:nth-of-type(1) {
    font-size: 4vw;
}

p:nth-of-type(2) {
    margin: 1vw auto;
    font-size: 1.5vw;
    width: 80%;
}
</style>